package com.getpebble.android.onboarding.fragment;

import android.accounts.Account;
import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.getpebble.android.R;
import com.getpebble.android.common.core.async.PblAsyncTask;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.common.framework.fragment.PblBaseFragment;
import com.getpebble.android.framework.notification.gmail.Gmail;
import com.getpebble.android.framework.notification.gmail.Gmail.LoginStatus;
import com.getpebble.android.framework.notification.gmail.GmailAddress;
import com.getpebble.android.main.sections.support.fragment.NotificationDemoFragment;
import com.getpebble.android.notifications.util.CoreNotifications;
import com.getpebble.android.onboarding.activity.OnboardingActivity;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.util.List;

public class SetupGmailAccountsFragment extends PblBaseFragment {
    private static final String TAG = SetupGmailAccountsFragment.class.getSimpleName();
    private Handler handleGmailLogin = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            String address = (String) msg.obj;
            switch (AnonymousClass3.$SwitchMap$com$getpebble$android$framework$notification$gmail$Gmail$LoginStatus[LoginStatus.values()[msg.what].ordinal()]) {
                case SMTPMessage.RETURN_FULL /*1*/:
                    Trace.verbose(SetupGmailAccountsFragment.TAG, "Permission required");
                    break;
                case SMTPMessage.RETURN_HDRS /*2*/:
                    Trace.verbose(SetupGmailAccountsFragment.TAG, "Play availability error");
                    if (SetupGmailAccountsFragment.this.getActivity() != null) {
                        GooglePlayServicesUtil.getErrorDialog(msg.arg1, SetupGmailAccountsFragment.this.getActivity(), 0).show();
                        break;
                    } else {
                        Trace.info(SetupGmailAccountsFragment.TAG, "activity is null");
                        return;
                    }
                case ListInfo.INDETERMINATE /*3*/:
                    Trace.verbose(SetupGmailAccountsFragment.TAG, "Login success!");
                    SetupGmailAccountsFragment.this.setGmailSyncPref(address, true);
                    if (SetupGmailAccountsFragment.this.getActivity() == null) {
                        Trace.info(SetupGmailAccountsFragment.TAG, "activity is null");
                        return;
                    }
                    break;
                case SMTPMessage.NOTIFY_DELAY /*4*/:
                    Trace.warning(SetupGmailAccountsFragment.TAG, "Credentials failed");
                    SetupGmailAccountsFragment.this.setGmailSyncPref(address, false);
                    if (SetupGmailAccountsFragment.this.getActivity() != null) {
                        Toast.makeText(SetupGmailAccountsFragment.this.getActivity(), R.string.gmail_auth_error, 1).show();
                        break;
                    } else {
                        Trace.info(SetupGmailAccountsFragment.TAG, "activity is null");
                        return;
                    }
                case R.styleable.WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance /*5*/:
                    Trace.error(SetupGmailAccountsFragment.TAG, "Unknown Error");
                    SetupGmailAccountsFragment.this.setGmailSyncPref(address, false);
                    if (SetupGmailAccountsFragment.this.getActivity() != null) {
                        Toast.makeText(SetupGmailAccountsFragment.this.getActivity(), R.string.gmail_unknown_error, 1).show();
                        break;
                    } else {
                        Trace.info(SetupGmailAccountsFragment.TAG, "activity is null");
                        return;
                    }
            }
            if (SetupGmailAccountsFragment.this.mLoggingInDialog != null && SetupGmailAccountsFragment.this.mLoggingInDialog.isShowing()) {
                SetupGmailAccountsFragment.this.mLoggingInDialog.dismiss();
            }
        }
    };
    private AccountAdapter mAdapter;
    private Context mAppContext;
    private Button mButtonFinished;
    private ProgressDialog mLoggingInDialog;
    private PblPreferences mPrefs;

    static /* synthetic */ class AnonymousClass3 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$notification$gmail$Gmail$LoginStatus = new int[LoginStatus.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$framework$notification$gmail$Gmail$LoginStatus[LoginStatus.PERMISSION_REQUIRED.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$notification$gmail$Gmail$LoginStatus[LoginStatus.PLAY_AVAILABILITY_ERROR.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$notification$gmail$Gmail$LoginStatus[LoginStatus.SUCCESS.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$notification$gmail$Gmail$LoginStatus[LoginStatus.CREDENTIALS_FAILED.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$notification$gmail$Gmail$LoginStatus[LoginStatus.UNKNOWN_ERROR.ordinal()] = 5;
            } catch (NoSuchFieldError e5) {
            }
        }
    }

    public class AccountAdapter extends ArrayAdapter<Account> {
        public AccountAdapter(Context context, List<Account> accounts) {
            super(context, R.layout.account_item, accounts);
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            final Account account = (Account) getItem(position);
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.account_item, parent, false);
            }
            TextView accountName = (TextView) convertView.findViewById(R.id.account_name);
            accountName.setText(account.name);
            final CheckBox accountEnabled = (CheckBox) convertView.findViewById(R.id.account_enabled_checkbox);
            OnClickListener listener = new OnClickListener() {
                public void onClick(View v) {
                    if (v != accountEnabled) {
                        accountEnabled.setChecked(!accountEnabled.isChecked());
                    }
                    if (accountEnabled.isChecked()) {
                        SetupGmailAccountsFragment.this.showGmailLoginDialogForAddress(account.name);
                    }
                    SetupGmailAccountsFragment.this.setGmailSyncPref(account.name, accountEnabled.isChecked());
                }
            };
            accountEnabled.setChecked(SetupGmailAccountsFragment.this.mPrefs.getSharedPreferences().getBoolean(SetupGmailAccountsFragment.this.mPrefs.prefKeyToString(PrefKey.GMAIL_ACCOUNT_ENABLED_PREFIX) + account.name, false));
            accountEnabled.setOnClickListener(listener);
            accountName.setOnClickListener(listener);
            return convertView;
        }
    }

    private class LoginTask extends PblAsyncTask {
        private String mAddress;

        LoginTask(String address) {
            this.mAddress = address;
        }

        public boolean doInBackground() {
            Gmail.validateNewAccount(SetupGmailAccountsFragment.this, SetupGmailAccountsFragment.this.handleGmailLogin, this.mAddress);
            return true;
        }

        public void onTaskSuccess() {
        }

        public void onTaskFailed() {
        }
    }

    public int getLayoutId() {
        return R.layout.fragment_gmail_accounts;
    }

    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.mButtonFinished = (Button) container.findViewById(R.id.gmail_button_finished);
        if (isOnboarding()) {
            this.mButtonFinished.setOnClickListener(new OnClickListener() {
                public void onClick(View view) {
                    SetupGmailAccountsFragment.this.goToNextFragment();
                }
            });
            if (checkThatAllGmailAccountsEnabled()) {
                Trace.verbose(TAG, "All accounts enabled; skipping");
                goToNextFragment();
            }
        } else {
            this.mButtonFinished.setVisibility(8);
        }
        Activity activity = getActivity();
        if (activity == null) {
            Trace.warning(TAG, "activity is null");
            return;
        }
        this.mPrefs = new PblPreferences(activity);
        ListView accountListview = (ListView) container.findViewById(R.id.accounts_list);
        this.mAdapter = new AccountAdapter(activity, GmailAddress.getAccountsList(activity.getApplicationContext()));
        accountListview.setAdapter(this.mAdapter);
        this.mAppContext = activity.getApplicationContext();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Gmail.REQUEST_CODE_AUTH && resultCode == -1) {
            String accountName = data.getStringExtra("authAccount");
            Trace.verbose(TAG, "Received RESULT_OK for " + accountName + " auth; requerying for token");
            new LoginTask(accountName).submit();
        }
    }

    private void goToNextFragment() {
        Activity activity = getActivity();
        if (activity instanceof OnboardingActivity) {
            OnboardingActivity onboardingActivity = (OnboardingActivity) activity;
            Bundle args = new Bundle();
            args.putBoolean("extra_is_onboarding", true);
            Fragment nextFragment = new NotificationDemoFragment();
            nextFragment.setArguments(args);
            onboardingActivity.switchScreenFragment(nextFragment);
        }
    }

    public void showGmailLoginDialogForAddress(String address) {
        Trace.verbose(TAG, "Showing gmail dialog for address: " + address);
        if (this.mLoggingInDialog == null) {
            this.mLoggingInDialog = new ProgressDialog(getActivity());
            this.mLoggingInDialog.setProgressStyle(0);
            this.mLoggingInDialog.setMessage(getResources().getText(R.string.gmail_pref_lstnr_logging_in).toString());
        }
        this.mLoggingInDialog.show();
        new LoginTask(address).submit();
    }

    public void setGmailSyncPref(String address, boolean enabled) {
        if (this.mAppContext == null) {
            Trace.error(TAG, "setGmailSyncPref: context was null");
            return;
        }
        PblPreferences preferences = new PblPreferences(this.mAppContext);
        Editor editor = preferences.getSharedPreferences().edit();
        editor.putBoolean(preferences.prefKeyToString(PrefKey.GMAIL_ACCOUNT_ENABLED_PREFIX) + address, enabled);
        editor.apply();
        this.mAdapter.notifyDataSetChanged();
        Trace.debug(TAG, "Gmail preference changed, calling update to disable if required");
        CoreNotifications.disableNotificationsForNativeApps(getActivity());
        CoreNotifications.updateAllowedStateForNativeApps(getActivity());
    }

    private boolean isOnboarding() {
        return getActivity() instanceof OnboardingActivity;
    }

    private boolean checkThatAllGmailAccountsEnabled() {
        Activity activity = getActivity();
        if (activity == null) {
            Trace.warning(TAG, "activity is null");
            return false;
        }
        List<Account> accounts = GmailAddress.getAccountsList(activity.getApplicationContext());
        PblPreferences prefs = new PblPreferences(activity);
        for (Account account : accounts) {
            if (!prefs.getSharedPreferences().getBoolean(prefs.prefKeyToString(PrefKey.GMAIL_ACCOUNT_ENABLED_PREFIX) + account.name, false)) {
                return false;
            }
        }
        return true;
    }
}
